import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet("/showRequest")
public class ShowRequest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StringBuilder result = new StringBuilder();
        //向字符串对象中拼接HTTP请求的名称和版本。
        result.append(req.getProtocol());
        result.append("<br>");

        //拼接HTTP请求的HTTP方法
        result.append(req.getMethod());
        result.append("<br>");

        //拼接URL中的一部分
        result.append(req.getRequestURI());
        result.append("<br>");

        //拼接查询字符串
        result.append(req.getQueryString());
        result.append("<br>");

        //拼接一级路径
        result.append(req.getContextPath());
        result.append("<br>");
        result.append("<h3>获取请求的header中的键值对</h3>");

        //这里获取getHeaderNames方法的返回值是一个枚举类型的值，所以使用枚举来接收
        Enumeration<String> headerNames = req.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            result.append(headerName + ": "+headerValue + "<br>");
        }


        //设置返回的响应的body的类型，方便浏览器进行解析
        resp.setContentType("text/html;charset=utf8");
        resp.getWriter().write(result.toString());


    }
}
